#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pii = pair<int, int>;
#define rep(i, a, b) for (int i = (a); i <= (b); i++)
#define per(i, a, b) for (int i = (a); i >= (b); i--)
#define endl '\n'
const int N = 6;

int n, m;
string a[N];
void solve() {
  rep(i, 0, 4) cin >> a[i];
  int ans = 10;
  rep(s, 0, 31) {
    int cnt = 0;
    bitset<5> op(0);
    bitset<5> pre(s);
    rep(i, 0, 4) {
      bitset<5> now(a[i]);
      cnt += pre.count();
      now ^= op;
      now ^= pre;
      now ^= pre << 1;
      now ^= pre >> 1;
      op = pre;
      pre = ~now;
    }
    if (pre.count() == 0) ans = min(ans, cnt);
  }
  if (ans <= 6)
    cout << ans << endl;
  else
    cout << -1 << endl;
}
int main() {
  ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
  int t;
  cin >> t;
  while (t--) solve();
  return 0;
}